package com.qf.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.mapper.UserMapper;
import com.qf.pojo.User;
import com.qf.service.IUserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements IUserService {

    private StringRedisTemplate template;

    @Autowired
    public void setTemplate(StringRedisTemplate template) {
        this.template = template;
    }

    private UserMapper userMapper;

    private ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public User findUserByID(Long id) throws JsonProcessingException {

//      先从redis缓存中查询
        String s = template.opsForValue().get("user"+id);
        if(s!=null){//证明缓存中有
//             转化成对象
            User user = objectMapper.readValue(s, User.class);
            return user;
        }

        User userByID = userMapper.findUserByID(id);
        template.opsForValue().set("user"+id, objectMapper.writeValueAsString(userByID));
        System.out.println("到这了");
        return userByID;
    }
}
